import React, { useRef, useState, useEffect } from "react";
import Cropper from "react-cropper";
import "cropperjs/dist/cropper.css";
// import './index.css';
import { UploadOutlined } from "@ant-design/icons";
import { Upload, Button, Space, Divider } from "antd";

function CropperComponent(props) {
    const cropperRef = useRef(null);
    const [imgsrc, setImgsrc] = useState(null); // 裁剪好的 imgsrc
    const { imgUrl } = props;

    // 使用 useEffect 来设置初始的 image 状态
    const [image, setImage] = useState(null);

    useEffect(() => {
        if (imgUrl) {
            setImage(imgUrl);
            console.log('Received imgUrl:', imgUrl);
        }
    }, [imgUrl]);

    const handleCrop = () => {
        const imageElement = cropperRef.current;
        const cropper = imageElement?.cropper;
        const back64Cropper = cropper.getCroppedCanvas().toDataURL();
        console.log(cropper.getCroppedCanvas().toDataURL("image/jpeg"), "裁剪的 base64 编码");
        const base64Data = back64Cropper;
        const url = base64ToUrl(base64Data);
        console.log("剪切 url=", url);
        setImgsrc(url);
    };

    function base64ToUrl(base64Data) {
        const blob = base64ToBlob(base64Data);
        const url = URL.createObjectURL(blob);
        return url;
    }

    function base64ToBlob(base64Data) {
        const byteString = atob(base64Data.split(",")[1]);
        const mimeString = base64Data.split(",")[0].split(":")[1].split(";")[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ab], { type: mimeString });
    }

    const replaceImg = (img) => {
        console.log(img.file, "img");
        const reader = new FileReader();
        reader.readAsDataURL(img.file.originFileObj);
        reader.onload = ({ target: { result } = {} }) => {
            console.log(result, "base64");
            setImage(result);
        };
        return false;
    };

    return (
        <div className="copy">
            {image ? (
                <div style={{ border: '1px solid red' }}>
                    <Cropper ref={cropperRef} src={image} style={{ height: "400px", width: "200px" }} />
                </div>
            ):(
                <p>No Image available</p>
            )}
            <div className="copy-but">
                <Space>
                    <Upload fileList={[]} onChange={replaceImg} accept="image/*">
                        <Button size="large" className="upload" icon={<UploadOutlined />}>
                            选择图片
                        </Button>
                    </Upload>
                    <Button size="large" className="button" type="primary" onClick={handleCrop}>
                        确定裁剪
                    </Button>
                </Space>
            </div>
            <div className="copy-img">
                <Divider plain>裁剪好的图片</Divider>
                <div
                    style={{
                        height: "200px",
                        width: "300px",
                        border: "1px solid #ccc",
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center",
                    }}
                >
                    <img style={{ width: "100%", height: "100%" }} src={imgsrc} />
                </div>
            </div>
        </div>
    );
}

export default CropperComponent;